package echat.future.cn.echat.home.network

import com.zhusx.core.debug.LogUtil
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

/**
 * Retrofits 工具类
 * Author        zhusx
 * Email         327270607@qq.com
 * Created       2016/12/6 9:07
 */
class Retrofits {
    companion object {
        @Volatile
        private var retrofit: Retrofit
        private const val BASE_HOST = "https://eliao-tv.com/"
        fun <T> createApi(clazz: Class<T>): T {
            return retrofit.create(clazz)
        }

        init {
            val client = OkHttpClient().newBuilder()
            val logging = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
                if (LogUtil.DEBUG) {
                    LogUtil.e(message)
                }
            })
            logging.level = HttpLoggingInterceptor.Level.BODY
            val sslContext = SSLContext.getInstance("TLS").apply {
                init(null, arrayOf<TrustManager>(object : X509TrustManager {
                    override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
                    }

                    override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
                    }

                    override fun getAcceptedIssuers(): Array<X509Certificate> {
                        return arrayOf()
                    }
                }), java.security.SecureRandom())
            }
            retrofit = Retrofit.Builder()
                    .client(client.addInterceptor(logging)
                            .sslSocketFactory(sslContext.socketFactory)
                            .hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                            .build())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .baseUrl(BASE_HOST)
                    .build()
        }
    }
}
